/**
 * 高度调整
 * @return {[type]} [description]
 */
function adjustHeight() {
    // 有滚动条
    if($(window).height() < $(document).height()) {
        // 小屏幕模式
        if($('#sidebar').width() == $('#main').width()) {
            $('#sidebar').css('height', 'auto');
        }
        else {
            $('#sidebar').height($(document).height());
        }
    }
    else {
        $('#sidebar').css('height', '100vh');
    }
}

function adjustMainWidth() {
    var main_width = $(document.body).width() - $('#sidebar').width() - 2;
    $('#main').width(main_width);
}

function adjustDragbar() {
    var $sidebar = $('#sidebar');
    var sl = $sidebar.scrollLeft();
    var $dragbar = $('#dragbar');
    var sw = parseInt($sidebar[0].style.width.replace('px', '')),
        dw = $dragbar.width();
    $dragbar.css('left', sw - dw + sl);
}

function resizable() {
    var i = 0;
    var dragging = false;
    $('#dragbar').mousedown(function (e) {
        e.preventDefault();

        dragging = true;
        var main = $('#main');
        var ghostbar = $('<div>', {
            id: 'ghostbar',
            css: {
                height: main.outerHeight(),
                // top: main.offset().top,
                left: main.offset().left
            }
        }).appendTo('body');

        $(document).mousemove(function (e) {
            var max_width = $(document.body).width();
            var _left = e.pageX + 2;
            if(_left < 50) {
                _left = 50;
            }
            var _max = parseInt(max_width / 2);
            if(_left > _max) {
                _left = _max;
            }
            ghostbar.css("left", _left);
        });
    });

    $(document).mouseup(function (e) {
        if (dragging) {
            var max_width = $(document.body).width();
            var _left = e.pageX + 2;
            if(_left < 50) {
                _left = 50;
            }
            var _max = parseInt(max_width / 2);
            if(_left > _max) {
                _left = _max;
            }
            // 设置宽度时会产生滚动条，所以先禁用掉
            $('html').addClass('no-scroll');
            $('#sidebar').css("width", _left);
            $('#main').css("left", _left);
            $('#ghostbar').remove();
            adjustDragbar();
            adjustMainWidth();
            // 页面宽度调整完毕，启用滚动条
            $('html').removeClass('no-scroll');
            $(document).unbind('mousemove');
            dragging = false;
        }
    });
    $('#sidebar').off('scroll').on('scroll', function(e) {
        adjustDragbar();
    });
}